﻿using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Collections.Specialized;
using EasyCommerce.DAL;
using CodeWork.Library;
using CodeWork.Library.Mail;
using log4net;
using System.Web;

/// <summary>
/// Summary description for MailManager
/// </summary>
namespace EasyCommerce.BLL
{
    public class MailManager
    {
        public MailManager() { }

        /// <summary>
        /// Copies Mail related settings into MailSettings object
        /// from Sitesettings object. A helpful time saving and
        /// code saving utility used by mostly mail senders
        /// </summary>
        /// <param name="siteSettings">Sitesettings object from where to load the settings</param>
        /// <returns>The loaded MailSettings object</returns>
        internal static MailSettings LoadMailSettings(Settings siteSettings)
        {
            MailSettings mailSettings = new MailSettings();
            mailSettings.AdminMail = siteSettings.AdminEmail;
            mailSettings.Password = siteSettings.SmtpPassword;
            mailSettings.Port = siteSettings.SmtpPort;
            mailSettings.ServerAddress = siteSettings.SmtpServer;
            mailSettings.SupportMail = siteSettings.SupportMail;
            mailSettings.UserName = siteSettings.SmtpUsername;
            mailSettings.UseSSL = siteSettings.SmtpUseSsl;

            return mailSettings;
        }

        /// <summary>
        /// Sends Registration mail after the new user registration.
        /// It is a confirmation mail that send the user credentials
        /// as well as a confirmation link to the mail for a returning
        /// user.
        /// </summary>
        /// <param name="siteSettings">Settings to use while sending mail</param>
        /// <param name="siteUser">The new user for whom to send the mail</param>
        /// <param name="userProfile">The user's profile for extra information</param>
        /// <returns>True if the mail is successfuly sent, otherwise false</returns>
        internal static bool SendRegistrationMail(Settings siteSettings, SiteUser siteUser, UserProfile userProfile)
        {
            if (siteSettings == null || siteUser == null || userProfile == null)
                return false;

            NameValueCollection nvc = new NameValueCollection();

            StringBuilder confirmationUrl = new StringBuilder();
            confirmationUrl.Append("http://");
            confirmationUrl.Append(siteSettings.CurrentDomain);
            confirmationUrl.Append("/public/activation.aspx?account=");
            confirmationUrl.Append(HttpUtility.UrlEncode(siteUser.UserName));
            confirmationUrl.Append("&confirmationCode=");
            confirmationUrl.Append(HttpUtility.UrlEncode(siteUser.ConfirmationCode));

            nvc.Add("ReceiverName", userProfile.FirstName + " " + userProfile.LastName);
            nvc.Add("ReceiverEmail", siteUser.EmailAddress);
            nvc.Add("Subject", siteSettings.SiteName + " - Registration Information");
            nvc.Add("<UserName>", siteUser.UserName);
            nvc.Add("<Password>", Security.Decrypt(siteUser.UserPassword, siteSettings.EncryptionKey, true));
            nvc.Add("<ConfirmationUrl>", confirmationUrl.ToString());
            nvc.Add("<SiteName>", siteSettings.SiteName);

            try
            {
                return MailSender.SendTemplatedMaill(LoadMailSettings(siteSettings), 
                    "/mailtemplates/RegisteredUser.txt", nvc);
            }
            catch (Exception ex)
            {
                ILog log = LogHelper.GetHandledFileLogger("MailManager");
                if (log.IsErrorEnabled)
                    log.Error("Could not send registration mail", ex);
                return false;
            }
        }

        internal static bool SendPasswordChangeMail(Settings siteSettings, SiteUser siteUser, 
            UserProfile userProfile, bool isReoverPassword)
        {
            if (siteSettings == null || siteUser == null || userProfile == null)
                return false;

            NameValueCollection nvc = new NameValueCollection();

            StringBuilder confirmationUrl = new StringBuilder();
            confirmationUrl.Append("http://");
            confirmationUrl.Append(siteSettings.CurrentDomain);

            if(isReoverPassword)
                confirmationUrl.Append("/public/recover.aspx?account=");
            else
                confirmationUrl.Append("/public/changepassword.aspx?account=");

            confirmationUrl.Append(HttpUtility.UrlEncode(siteUser.UserName));
            confirmationUrl.Append("&confirmationCode=");
            confirmationUrl.Append(HttpUtility.UrlEncode(siteUser.ConfirmationCode));

            nvc.Add("ReceiverName", userProfile.FirstName + " " + userProfile.LastName);
            nvc.Add("ReceiverEmail", siteUser.EmailAddress);
            nvc.Add("Subject", siteSettings.SiteName + " - Password Recovery");
            nvc.Add("<UserName>", siteUser.UserName);
            nvc.Add("<PasswordRecoverUrl>", confirmationUrl.ToString());
            nvc.Add("<SiteName>", siteSettings.SiteName);

            try
            {
                return MailSender.SendTemplatedMaill(LoadMailSettings(siteSettings), 
                    "/mailtemplates/ChangePassword.txt", nvc);
            }
            catch (Exception ex)
            {
                ILog log = LogHelper.GetHandledFileLogger("MailManager");
                if (log.IsErrorEnabled)
                    log.Error("Could not send password recovery mail", ex);
                return false;
            }
        }

        /// <summary>
        /// Sends notification mail after the user password is successfuly changed.
        /// </summary>
        /// <param name="siteSettings">Settings for the website</param>
        /// <param name="siteUser">User for whom the password has been changed</param>
        /// <param name="userProfile">Profile of the user, holds additional information</param>
        /// <returns>True if mail is successfuly sent, false otherwise</returns>
        internal static bool SendPasswordChangeInformationMail(Settings siteSettings, SiteUser siteUser,
            UserProfile userProfile)
        {
            if (siteSettings == null || siteUser == null || userProfile == null)
                return false;

            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("ReceiverName", userProfile.FirstName + " " + userProfile.LastName);
            nvc.Add("ReceiverEmail", siteUser.EmailAddress);
            nvc.Add("Subject", siteSettings.SiteName + " - Password Changed");
            nvc.Add("<UserName>", siteUser.UserName);
            nvc.Add("<Password>", Security.Decrypt(siteUser.UserPassword, siteSettings.EncryptionKey, true));
            nvc.Add("<SiteName>", siteSettings.SiteName);

            try
            {
                return MailSender.SendTemplatedMaill(LoadMailSettings(siteSettings),
                    "/mailtemplates/PasswordChangedInformation.txt", nvc);
            }
            catch (Exception ex)
            {
                ILog log = LogHelper.GetHandledFileLogger("MailManager");
                if (log.IsErrorEnabled)
                    log.Error("Could not send password recovery mail", ex);
                return false;
            }
        }
    }
}